#!/usr/bin/env python

import argparse
import os
import platform
import subprocess
import sys

from lib.util import get_vs_env


SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
# We're in JENKINS_ROOT/workspace/libchromiumcontent. Walk up to JENKINS_ROOT.
JENKINS_ROOT = os.path.dirname(os.path.dirname(SOURCE_ROOT))
S3_CREDENTIALS_FILE = os.path.join(JENKINS_ROOT, 'config', 's3credentials')


def main():
  args = parse_args()
  skip_upload = args.skip_upload
  use_sccache = args.use_sccache
  build_tests = args.build_tests

  if (not skip_upload and
     not 'LIBCHROMIUMCONTENT_S3_ACCESS_KEY' in os.environ and
     not 'LIBCHROMIUMCONTENT_S3_BUCKET' in os.environ and
     not 'LIBCHROMIUMCONTENT_S3_SECRET_KEY' in os.environ):
     if os.path.isfile(S3_CREDENTIALS_FILE):
       copy_to_environment(S3_CREDENTIALS_FILE)
     else:
       skip_upload = True
  if (skip_upload):
    print 'WARNING: Upload to S3 will be skipped.'
  # Use by gclient to distinguish bot builds
  os.environ['CHROME_HEADLESS'] = '1'

  component = None
  if 'TARGET_ARCH' in os.environ:
    archs = [os.environ['TARGET_ARCH']]
    component = os.environ['COMPONENT']
  elif sys.platform in ['win32', 'cygwin']:
    archs = ['x64', 'ia32']
  elif sys.platform == 'linux2':
    archs = ['x64', 'ia32', 'arm', 'arm64']
  else:
    archs = [None]

  ci_results = True
  for arch in archs:
    if not run_ci(arch, skip_upload, use_sccache, build_tests, component):
      return False

    return True

def parse_args():
  parser = argparse.ArgumentParser(description='Run CI build')
  parser.add_argument('-s', '--skip_upload', action='store_true',
                      help='Skip uploading to S3')
  parser.add_argument('--use_sccache', action='store_true',
                      help='Use sccache binary stored in with the libcc repo.')
  parser.add_argument('--build_tests', action='store_true',
                      help='Build tests as part of build.')
  return parser.parse_args()

def copy_to_environment(credentials_file):
    with open(credentials_file, 'r') as f:
        for line in f:
            key, value = line.strip().split('=')
            key = key.replace('JANKY_ARTIFACTS_', 'LIBCHROMIUMCONTENT_')
            value = value.strip("'")
            os.environ[key] = value


def os_version():
  if sys.platform in ['win32', 'cygwin']:
    return platform.system() + ' ' + platform.release() + ' ' + platform.version()
  elif sys.platform == 'darwin':
    mac_ver = platform.mac_ver()
    return 'Mac OS X ' + mac_ver[0] + ' ' + mac_ver[2]
  else:
    return platform.platform()


def run_ci(target_arch, skip_upload, use_sccache, build_tests, component=None):
  args = []
  if target_arch is not None:
    args += ['-t', target_arch]
  build_args = []
  component_args = []
  update_args = ['--clean', '--use_packaged_src'] + args
  if use_sccache:
    update_args += ['--use-bundled-sccache']
  if target_arch == 'x64' and component == 'shared_library':
    update_args += ['--upload_packaged_src']
  if component is not None:
    component_args = ['-c', component]
    build_args += component_args + ['ffmpeg']
    if build_tests:
      build_args += ['tests']
  if sys.platform in ['win32', 'cygwin']:
    # Set build env for VS.
    if target_arch == 'x64':
      vs_env = get_vs_env('14.0', 'x86_amd64')
    elif target_arch == 'ia32':
      vs_env = get_vs_env('14.0', 'amd64_x86')
    os.environ.update(vs_env)

  return (run_script('bootstrap') or
          run_script('update', update_args) or
          run_script('build', args + build_args) or
          run_script('create-dist', args + component_args) or
          run_script('upload', args, skip_upload))


def run_script(script, args=[], skip_run=False):
  if skip_run:
    return 0
  script = os.path.join('script', script)
  sys.stderr.write('+ {0}\n'.format(script))
  sys.stderr.flush()
  return subprocess.call([sys.executable, script] + args)


if __name__ == '__main__':
    sys.exit(main())
